package com.hdl.util;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

/**
 * 数据库连接工具类
 */
public class JdbcUtil {

    private static String username;
    private static String password;
    private static String url;
    private static String driver;

    static {
        try {

            Properties pro = new Properties();

            //加载配置文件
            URL resource = JdbcUtil.class.getClassLoader().getResource("druid.properties");

            pro.load(new FileReader(resource.getPath()));

            //获取值
            username = pro.getProperty("username");
            password = pro.getProperty("password");
            url = pro.getProperty("url");
            driver = pro.getProperty("driverClassName");

            //注册驱动
            Class.forName(driver);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接对象
     * @return 数据库连接对象
     * @throws SQLException
     */
    public static Connection getConnection() {
    	     Connection con=null;
        try {
			con= DriverManager.getConnection(url,username,password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return con;
    }

    /**
     * 释放资源
     * @param statement sql语句对象
     * @param connection 数据库连接对象
     */
    public static void close(Statement statement, Connection connection){
        close(null,statement,connection);
    }

    /**
     * 释放资源
     * @param resultSet 结果集对象
     * @param statement sql语句对象
     * @param connection 数据库连接对象
     */
    public static void close(ResultSet resultSet, Statement statement, Connection connection){

         if(resultSet != null){
             try {
                 resultSet.close();
             }catch (Exception e){
                 e.printStackTrace();
             }
         }

        if(statement != null){
            try {
                statement.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        if(connection != null){
            try {
                connection.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    
    /**
     * -随机生成一个ID
     */
    private static Snowflake id = IdUtil.getSnowflake(0, 0);
	
	public static long nextId() {
		return id.nextId();
	}
	
	/**
	 * 设置预编译语句的所有参数
	 * 
	 * @param pstmt
	 * @param objects
	 * @throws SQLException
	 */
	public static void setParams(PreparedStatement pstmt, Object... objects) throws SQLException {
		for (int i = 0; i < objects.length; i++) {
			pstmt.setObject(i + 1, objects[i]);
		}
	}
}
